import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Server, ServerDetail, ServerListParams, ReadmeResponse } from '@/types/server'
import * as serverApi from '@/api/server'

export const useServerStore = defineStore('server', () => {
  //  Server 列表相关状态
  const servers = ref<Server[]>([])
  const totalCount = ref<number>(0)
  const currentPage = ref<number>(1)
  const pageSize = ref<number>(12)
  const loading = ref<boolean>(false)
  const error = ref<string | null>(null)
  
  //  Server 详情相关状态
  const currentServer = ref<ServerDetail | null>(null)
  const readmeContent = ref<string>('')
  const detailLoading = ref<boolean>(false)
  const detailError = ref<string | null>(null)
  
  // 搜索和过滤相关状态
  const searchQuery = ref<string>('')
  const selectedCategory = ref<string>('')
  const selectedTags = ref<string[]>([])
  const selectedProvider = ref<string>('')
  const isInternal = ref<boolean | null>(null)
  const isOfficial = ref<boolean | null>(null)
  const accessMode = ref<string>('')
  const sortBy = ref<string>('name')
  
  // 计算属性：搜索参数
  const searchParams = computed<ServerListParams>(() => {
    const params: ServerListParams = {
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value,
      category: selectedCategory.value,
      tags: selectedTags.value,
      provider: selectedProvider.value,
      ordering: sortBy.value
    }
    
    if (isInternal.value !== null) {
      params.is_internal = isInternal.value
    }
    
    if (isOfficial.value !== null) {
      params.is_official = isOfficial.value
    }
    
    if (accessMode.value && accessMode.value.length > 0) {
      params.access_mode = accessMode.value
    }
    
    return params
  })
  
  // 获取 Server 列表
  async function fetchServers() {
    loading.value = true
    error.value = null
    
    try {
      const response = await serverApi.getServers(searchParams.value)
      servers.value = response.results
      totalCount.value = response.count
      return response.results
    } catch (err: any) {
      error.value = err.message || '获取 Server 列表失败'
      return []
    } finally {
      loading.value = false
    }
  }
  
  // 获取内部 Server 列表
  async function fetchInternalServers() {
    const savedIsInternal = isInternal.value
    isInternal.value = true
    
    loading.value = true
    error.value = null
    
    try {
      const response = await serverApi.getServers(searchParams.value)
      servers.value = response.results
      totalCount.value = response.count
      return response.results
    } catch (err: any) {
      error.value = err.message || '获取内部 Server 列表失败'
      return []
    } finally {
      loading.value = false
      isInternal.value = savedIsInternal
    }
  }
  
  // 获取 Server 详情
  async function fetchServerDetail(id: string) {
    detailLoading.value = true
    detailError.value = null
    
    try {
      const detail = await serverApi.getServerById(id)
      currentServer.value = detail
      return detail
    } catch (err: any) {
      detailError.value = err.message || '获取 Server 详情失败'
      return null
    } finally {
      detailLoading.value = false
    }
  }
  
  // 获取README内容
  async function fetchReadme(id: string) {
    try {
      const response: ReadmeResponse = await serverApi.getServerReadme(id)
      readmeContent.value = response.content
      return response.content
    } catch (err: any) {
      console.error('获取README失败', err)
      readmeContent.value = ''
      return ''
    }
  }
  
  // 创建新 Server 
  async function createServer(data: Partial<Server>) {
    try {
      const newServer = await serverApi.createServer(data)
      await fetchServers() // 重新获取列表
      return newServer
    } catch (err: any) {
      console.error('创建 Server 失败', err)
      throw err
    }
  }
  
  // 更新 Server 信息
  async function updateServer(id: string, data: Partial<Server>) {
    try {
      const updatedServer = await serverApi.updateServer(id, data)
      
      // 如果当前查看的就是这个 Server ，则更新当前 Server 信息
      if (currentServer.value && currentServer.value.id === id) {
        currentServer.value = { ...currentServer.value, ...updatedServer }
      }
      
      // 更新列表中的 Server 信息
      const index = servers.value.findIndex(s => s.id === id)
      if (index !== -1) {
        servers.value[index] = { ...servers.value[index], ...updatedServer }
      }
      
      return updatedServer
    } catch (err: any) {
      console.error('更新 Server 失败', err)
      throw err
    }
  }
  
  // 删除 Server 
  async function deleteServer(id: string) {
    try {
      await serverApi.deleteServer(id)
      
      // 从列表中移除
      servers.value = servers.value.filter(s => s.id !== id)
      
      // 如果当前查看的就是这个 Server ，则清空当前 Server 
      if (currentServer.value && currentServer.value.id === id) {
        currentServer.value = null
      }
      
      return true
    } catch (err: any) {
      console.error('删除 Server 失败', err)
      throw err
    }
  }
  
  // 设置页码
  function setPage(page: number) {
    currentPage.value = page
  }
  
  // 设置搜索查询
  function setSearchQuery(query: string) {
    searchQuery.value = query
    currentPage.value = 1 // 重置页码
  }
  
  // 设置分类
  function setCategory(category: string) {
    selectedCategory.value = category
    currentPage.value = 1
  }
  
  // 设置标签
  function setTags(tags: string[]) {
    selectedTags.value = tags
    currentPage.value = 1
  }
  
  // 添加标签
  function addTag(tag: string) {
    if (!selectedTags.value.includes(tag)) {
      selectedTags.value.push(tag)
      currentPage.value = 1
    }
  }
  
  // 移除标签
  function removeTag(tag: string) {
    selectedTags.value = selectedTags.value.filter(t => t !== tag)
    currentPage.value = 1
  }
  
  // 设置是否内部
  function setIsInternal(value: boolean | null) {
    isInternal.value = value
    currentPage.value = 1
  }
  
  // 设置是否官方
  function setIsOfficial(value: boolean | null) {
    isOfficial.value = value
    currentPage.value = 1
  }
  
  // 设置访问模式
  function setAccessMode(modes: string) {
    accessMode.value = modes
    currentPage.value = 1
  }
  
  // 设置排序方式
  function setSortBy(sort: string) {
    sortBy.value = sort
  }
  
  // 重置过滤条件
  function resetFilters() {
    searchQuery.value = ''
    selectedCategory.value = ''
    selectedTags.value = []
    selectedProvider.value = ''
    isInternal.value = null
    isOfficial.value = null
    accessMode.value = null
    sortBy.value = 'name'
    currentPage.value = 1
  }
  
  // 重置数据状态
  function resetData() {
    servers.value = []
    totalCount.value = 0
    currentPage.value = 1
    loading.value = false
    error.value = null
  }
  
  return {
    // 状态
    servers,
    totalCount,
    currentPage,
    pageSize,
    loading,
    error,
    currentServer,
    readmeContent,
    detailLoading,
    detailError,
    searchQuery,
    selectedCategory,
    selectedTags,
    selectedProvider,
    isInternal,
    isOfficial,
    accessMode,
    sortBy,
    
    // 计算属性
    searchParams,
    
    // 方法
    fetchServers,
    fetchInternalServers,
    fetchServerDetail,
    fetchReadme,
    createServer,
    updateServer,
    deleteServer,
    setPage,
    setSearchQuery,
    setCategory,
    setTags,
    addTag,
    removeTag,
    setIsInternal,
    setIsOfficial,
    setAccessMode,
    setSortBy,
    resetFilters,
    resetData
  }
}) 